package com.xlongwei.todays.config;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;

import org.noear.solon.Utils;

import com.cronutils.model.Cron;
import com.cronutils.model.CronType;
import com.cronutils.model.definition.CronDefinition;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.model.time.ExecutionTime;
import com.cronutils.parser.CronParser;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CronUtils {
    public static final CronDefinition define = CronDefinitionBuilder.instanceDefinitionFor(CronType.CRON4J);
    public static final CronParser parser = new CronParser(define);

    /**
     * 校验todo的cron字段是否有效
     * 
     * @param cron 示例：* * * * *
     * @return
     */
    public static boolean valid(String cron) {
        return cron(cron) != null;
    }

    public static Cron cron(String cron) {
        try {
            return Utils.isBlank(cron) ? null : parser.parse(cron).validate();
        } catch (Exception e) {
            return null;
        }
    }

    public static ZonedDateTime next(String cron, LocalDate today) {
        ZonedDateTime start = today.atStartOfDay(ZoneId.systemDefault());
        Cron obj = cron(cron);
        if (obj != null) {
            ExecutionTime et = ExecutionTime.forCron(obj);
            ZonedDateTime next = et.nextExecution(start).orElse(start);
            return next;
        }
        return start;
    }
}
